package com.usian.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.usian.UserFeign;
import com.usian.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("consumer")
public class ConUserController {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Autowired
    private UserFeign userFeign;


    @GetMapping("findById")
    public User findById(Integer id){
        //找注册中心获取服务实例
        ServiceInstance instance=loadBalancerClient.choose("nacos-provider");
        //拼接访问地址 http://192.168.31.139:9090/user/findById/7
        String url="http://"+instance.getHost()+":"+instance.getPort()+"/user/findById/"+id;
        //发起调用
        User user=restTemplate.getForObject(url,User.class);
        return user;


    }
    @GetMapping("findByIds")
    @SentinelResource(value = "findByIds",blockHandler = "test",fallback = "fallMethod")
    public User findByIds(Integer id,String name){
        int a=1/0;
     User user=userFeign.findById(id,name);
     return user;
    }

    public User test(Integer idm, String name, BlockException b){
        System.out.println("111111111111");
        return  new User(5,"访问用户过多，请稍后试试",10);
    }
    public User fallMethod(Integer id,String name){
        return  new User(6,"访问用户过多fall，请稍后试试",60);

    }

    @GetMapping("findByIdda")
    public User findByIdda(Integer id,String name ){
        User user=userFeign.findByIdd(id,name);
        return user;
    }
    @PostMapping("findByUser")
    public User findByUser(@RequestBody User user){
        System.out.println(user.toString());
        return  userFeign.findByUser(user);
    }


}
